如果我們把方法作為參數傳遞給方法,就會用到委託~
委託大致有三個步驟~
第一是委託宣告 ~ 第二是方法塞入 ~ 第三是委託調用 ~
那我們來看委託是如何被實現的吧 ~
學習目標: Delegate and Events的概念
學習難度: ☆☆☆
using System;
namespace ConsoleApp1
{
class MainProgram
{
public delegate void Project(string name); //委託宣告
static void GameFactory1(string name)
{
Console.WriteLine(name + "made by GameFactory1");
}
static void GameFactory2(string name)
{
Console.WriteLine(name + "made by GameFactory2");
}
static void Main(string[] args)
{
//方法塞入委派
Project task1 = new Project(GameFactory1);
//方法塞入委派
Project task2 = GameFactory2;
//方法塞入委派
Project task3 = (string name) => Console.WriteLine(name + "made by students");
task1("car game"); //調用委派
task1("gun game"); //調用委派
task1("RPG game"); //調用委派
}
}
}
接著來看到事件~ 事件是一個對象發送的通知~ 表示發生一個動作~
當事件方送通知後~ 委派會去執行它的任務~
那我們來看事件是如何被實現的吧 ~
using System;
namespace ConsoleApp1
{
public delegate void Project(string name); // 專案委派
public class ProjectEvent
{
public event Project NewProject; // 專案事件
public void ProjectStart(string name) // 專案介紹
{
Console.WriteLine("Project name is" + " " + name);
ProjectState(name); // 專案狀態
}
protected virtual void ProjectState(string name) //protected virtual method
{
//if NewProject is Game then call delegate
if (name == "Game")
{
NewProject.Invoke(name); //呼叫委派
}
else
{
Console.WriteLine("Project is not a game !");
}
}
}
class MainProgram
{
// event handler
public static void ProjectState(string name)
{
Console.WriteLine($"{name} Project is Active !");
}
public static void Main()
{
ProjectEvent project = new ProjectEvent();
project.NewProject += ProjectState; //註冊事件
project.ProjectStart("Game"); //啟動遊戲專案
project.ProjectStart("DataBase"); //啟動資料庫專案
}
}
}
參考資料:
https://www.tutorialsteacher.com/csharp/csharp-delegates
https://www.tutorialsteacher.com/csharp/csharp-event
https://ithelp.ithome.com.tw/articles/10228906